package com.gjs.freechat.web.utils;


import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.web.util.WebUtils;
import org.w3c.dom.Attr;

public class MyWebUtils {
	
	public static String getCookieValue(Cookie[] cookies, String name) {
		for (int i = 0; i < cookies.length; i++) {
			if (cookies[i].getName().equals(name)) {
				return cookies[i].getValue();
			}
		}
		return null;
	}
	
	public static String getRequestBasePath(HttpServletRequest request) {
		String path = request.getContextPath();
		String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
		return basePath;
	}
	
	public static void setBasePathToServletContext(HttpServletRequest request) {
		String basePath = getRequestBasePath(request);
		if (getServletContextAttr(request, "basePath") == null) {
			setServletContextAttr(request, "basePath", basePath);
		}
	}
	
	private static String CX_PATH = ""; 
	public static void setServletContextPath(ServletContext context) {
		CX_PATH = context.getContextPath();
		if (CX_PATH.length() == 0) 
			CX_PATH = "/";
	}
	public static String getContextPath() {
		return CX_PATH;
	}
	
	public static Object getServletContextAttr(HttpServletRequest request, String name) {
		return request.getServletContext().getAttribute(name);
	}
	
	public static void setServletContextAttr(HttpServletRequest request, String name, Object value) {
		request.getServletContext().setAttribute(name, value);
	}
	
	public static void setServletContextAttr(ServletConfig servletConfig, String name, Object value) {
		servletConfig.getServletContext().setAttribute(name, value);
	}
	
	public static void setServletContextAttr(ServletContext servletContext, String name, Object value) {
		servletContext.setAttribute(name, value);
	}
	
	public static void setHttpSessionAttrs(HttpSession session, Map<String, Object> atts) {
		for (Entry<String, Object> entry : atts.entrySet()) {
			session.setAttribute(entry.getKey(), entry.getValue());
		}
	}
	
	public static Object getHttpSessionAttr(HttpServletRequest request, String name) {
		return request.getSession().getAttribute(name);
	}
	
	public static void main(String[] args) {
		System.out.println("d7127c6e-b1f0-4cd1-b711-7938d665bc02".length());
	}

}
